%automicT.m

function T=automicT(m)

gray_min = double(min(m(:)));
gray_max = double(max(m(:)));
gray_range = gray_max-gray_min+1;
offset = abs(gray_min);
histogram = zeros(1,gray_range);
[row,col]=size(m);
for i = 1:512
    for j = 1:512
        temp_gray = m(i,j);
        index = temp_gray+offset+1 ; 
        histogram(index) = histogram(index)+1;
    end
end

T0=gray_range/2;
b1=0;
b2=0;
a1=0;
a2=0;
for i=1:gray_range
    if i<=T0
        b1 = b1+histogram(i);
        a1 = a1+i*(histogram(i));
    end
    if i>T0
        b2 = b2+histogram(i);
        a2 = a2+i*(histogram(i));
    end
end
T1=(a1/b1+a2/b2)/2;
while(T1~=T0)
    b1=0;
    b2=0;
    a1=0;
    a2=0;
    for i=1:gray_range
        if i<=T1
            b1 = b1+histogram(i);
            a1 = a1+i*(histogram(i));
        end
        if i>T1
            b2 = b2+histogram(i);
            a2 = a2+i*(histogram(i));
        end
    end
    T0=T1;
    T1=(a1/b1+a2/b2)/2;
end

T=T1;
    
    
    
    


